<?php

$expense_obj = new expense_obj();
$user_obj = new user_obj();

if (!empty($_REQUEST['message'])) {
    if ($_REQUEST['message'] == 'added')
        error_obj::setGood('New expense of user was added.');
}

if (isset($_REQUEST['action'])) {
    switch ($_REQUEST['action']) {
        case 'deleteExpenses':
            if (!empty($_REQUEST['expenseId'])) {
                $success = true;
                foreach ($_REQUEST['expenseId'] as $key => $id) {
                    $res = $expense_obj->deleteExpenseById($id);
                    if (error_obj::isError($res)) {
                        error_obj::setError($res, UNEXCEPTED);
                        $success = false;
                    }
                }
                if ($success) {
                    error_obj::setGood("Expenses were deleted!");
                    base_obj::redirect(ROOT . '?input=fixed_expense');
                }
            }
            break;
    }
}

$list = $expense_obj->getExpensesGroupByUser();

if (error_obj::isError($list)) {
    error_obj::setError($list, UNEXCEPTED);
} elseif (!empty($list)) {
    $GLOBALS['template_data']['expenses'] = array();
    foreach ($list as $userId => $expenses) {
        $user = $user_obj->getUserById($userId);
        foreach ($expenses as $key => $value) {
            $expenses[$key]['from'] = base_obj::convertDateTo($value['from'], "dd.mm.yyyy", 'date');
        }
        $GLOBALS['template_data']['expenses'][$user['name'] . " " . $user['surname']] = $expenses;
    }
}
?>
